package com.qfedu.zf.user.controller;
import cn.hutool.core.convert.NumberWithFormat;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.zf.common.config.RedisKeyConfig;
import com.qfedu.zf.common.config.SystemConfig;
import com.qfedu.zf.common.param.Listings;
import com.qfedu.zf.common.param.UserAdd;
import com.qfedu.zf.common.param.UserLogin;
import com.qfedu.zf.common.utils.JwtUtil;
import com.qfedu.zf.common.vo.R;
import com.qfedu.zf.user.entity.Images;
import com.qfedu.zf.user.entity.User;
import com.qfedu.zf.user.mapper.ImagesMapper;
import com.qfedu.zf.user.mapper.ListingsMapper;
import com.qfedu.zf.user.mapper.UserMapper;
import com.qfedu.zf.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 1.用户表 前端控制器
 * </p>
 *
 * @author wgz
 * @since 2024-06-05
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ListingsMapper listingsMapper;

    @Autowired
    private ImagesMapper imagesMapper;

    /**
     * 根据用户id 查询用户信息
     * listing页面显示房东信息
     * @param map
     * @return
     */
    @RequestMapping("/listingUser")
    public R listingUser(@RequestParam Map<String,Object> map){
        if (map.get("userId")==null) {
            return R.fail("未知的房源");
        }
        return userService.listingUser(map);
    }


    @RequestMapping("/register")
    public R register(HttpServletRequest request, @RequestBody UserAdd userAdd){

       return userService.register(request,userAdd);
    }

    /**
     * 使用 账号 + 密码登录
     * 1.判断参数是否为空
     * 2.判断账户是存在，可用
     * 3.判断登录次数是否超过三次
     * 4.验证用户 密码
     *
     * 5.生成token
     * 6.存储token
     * 7.记录登录日志
     * 8.返回token
     *
     * @return
     */
    @RequestMapping("/loginPass")
    public R loginPass(@RequestBody UserLogin userLogin){


        return userService.loginPass(userLogin);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public R logout(HttpServletRequest request){
        String token = request.getHeader(SystemConfig.HEADER_TOKEN);
        return userService.logout(token);
    }

    @RequestMapping(value = "/selectById",method = RequestMethod.GET)
    public R selectById(HttpServletRequest request){
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        User user = userMapper.selectById(id);
        return R.ok(userMapper.selectById(id));
    }

    @RequestMapping(value = "/editNickname",method = RequestMethod.GET)
    public R editNickname(HttpServletRequest request, @RequestParam("nickname") String nickename){
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        User user = userMapper.selectById(id);
        user.setNickname(nickename);
        userMapper.updateById(user);
        return R.ok(user);
    }

    @RequestMapping(value = "/editPhone",method = RequestMethod.GET)
    public R editPhone(HttpServletRequest request,@RequestParam("code") String code,@RequestParam("phone") String phone){
        String redisCode = stringRedisTemplate.opsForValue().get(RedisKeyConfig.SMS_RCODE+phone);
        if (!code.equals(redisCode)){// 注意顺序更换可能导致空指针(redis有效期)
            return R.fail("验证码错误");
        }
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        User user = userMapper.selectById(id);
        user.setPhone(phone);
        userMapper.updateById(user);
        return R.ok(user);
    }

    @RequestMapping(value = "/editAvatar",method = RequestMethod.GET)
    public R editAvatar(HttpServletRequest request,String url){
        System.out.println(url);
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer id = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        User user = userMapper.selectById(id);
        user.setAvatar(url);
        userMapper.updateById(user);
        return R.ok(user);
    }

    @RequestMapping(value = "/posting",method = RequestMethod.POST)
    public R addListing(@RequestBody Listings listing,HttpServletRequest request){
        com.qfedu.zf.user.entity.Listings listings = new com.qfedu.zf.user.entity.Listings();
        listings.setDescription(listing.getDescription());
        listings.setHouseType(listing.getHouseType());
        listings.setPrice(listing.getPrice());
        listings.setCover(listing.getUrl());
        String header = request.getHeader(SystemConfig.HEADER_TOKEN);
        Integer userId = ((NumberWithFormat) JwtUtil.parseToken(header, "id")).intValue();
        listings.setUserId(userId);
        // 插入记录，ID会自动设置到listings对象的id属性上
        listingsMapper.insert(listings);
        // 现在listings.getId()将返回新插入记录的ID
        int id = listings.getListingId();

        Images images = new Images();
        images.setImageUrl(listing.getUrl());
        images.setListingId(id);
        imagesMapper.insert(images);

        return R.ok(listing);
    }

    @RequestMapping(value = "/listing")
    public R listing(@RequestParam("id") String id){
        QueryWrapper<com.qfedu.zf.user.entity.Listings> listingsQueryWrapper = new QueryWrapper<>();
        listingsQueryWrapper.eq("user_id",id);
        List<com.qfedu.zf.user.entity.Listings> listings = listingsMapper.selectList(listingsQueryWrapper);
        return R.ok(listings);
    }
    @RequestMapping(value = "/list")
    public R selectUserList(){
        return R.ok(userMapper.selectList(null));
    }

    @RequestMapping(value = "/listingDelete")
    public R listingDelete(@RequestParam("id") String id){
        return R.ok(listingsMapper.deleteById(id));
    }
}

